import json
import os
import random
import time

from pynput.keyboard import Key, Controller
import pyperclip

keyword = Controller()

config = {
    "start": 5,
    "random": False,
    "speed": 0,
    "line_interval": 0,
    "space_interval": 0,
    "input_file": "./input.txt",
    "default_file": "./input.txt"
}


def read_config():
    if not os.path.exists("auto_input_config.json"):
        pass
    with open("auto_input_config.json", "r") as f:
        read_configs = json.loads(f.read())

        for key in read_configs:
            config[key] = read_configs[key]


def input_line(line: str):
    for ch in line:
        keyword.press(ch)
        keyword.release(ch)
        print(ch, end='')

        if config["random"]:
            time.sleep(random.random())
        elif ch == ' ':
            time.sleep(config["space_interval"])
        else:
            time.sleep(config["speed"])

    keyword.press(Key.enter)
    keyword.release(Key.enter)
    print("")

    time.sleep(config["line_interval"])


def main():
    lines = []
    if os.path.exists(config["input_file"]):
        with open(config["input_file"], "r", encoding="utf-8") as f:
            lines = f.read().split('\n')
        print("From Config File, File Name: {}".format(config["input_file"]))
    elif os.path.exists(config["default_file"]):
        with open(config["default_file"], "r", encoding="utf-8") as f:
            lines = f.read().split('\n')
        print("From Default File, File Name: {}".format(config["default_file"]))
    else:
        lines = pyperclip.paste().split('\r\n')
        print("From Paste Text")

    print("Input Text: \n")
    for line in lines:
        input_line(line)


if __name__ == '__main__':
    read_config()
    print("Auto Input Start Time: {}".format(config["start"]))
    time.sleep(config["start"])
    main()
    print("\nAuto Input End, Welcome To Use!")
